package com.rabbitmq.controller;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class Provider {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 直连
     */
    @ResponseBody
    @RequestMapping("/send")
    public String send() {

        String msg = "hello";
        rabbitTemplate.convertAndSend("myDirectExchange", "my.direct.routing", msg);

        return "success";
    }

    /**
     * 扇形
     */
    @ResponseBody
    @RequestMapping("/sendByFanout")
    public String sendByFanout() {

        String msg = "hello fanout";
        rabbitTemplate.convertAndSend("fanoutExchange", null, msg);

        return "success";
    }

    /**
     * 主题
     */
    @ResponseBody
    @RequestMapping("/sendByTopic")
    public String sendByTopic(@RequestParam(required = true, defaultValue = "1") Integer type) {

        if(type == 1){

            String msg = "hello topic.01";
            // myTopicQueue_01 myTopicQueue_02都会收到消息
            rabbitTemplate.convertAndSend("myTopicExchange", "topic.01", msg + " topic.01");

        }else if(type == 2){
            String msg2 = "hello topic.xxx";
            // 只有队列 myTopicQueue_02才能收到消息
            rabbitTemplate.convertAndSend("myTopicExchange", "topic.xxx", msg2 + " topic.xxx");
        }

        return "success";
    }
}
